package com.example.word.util;


import android.util.Log;

/**
 * @author xujunwei
 */
public class ExceptionUtils {

    /**
     * 获取异常详情 格式化成string
     *
     * @param throwable ·
     * @return ·
     */
    public static String getExceptionDetail(Throwable throwable) {
        StringBuilder sb = new StringBuilder("发生异常,异常详细信息为: ");
        sb.append(throwable);
        StackTraceElement[] traceElements = throwable.getStackTrace();
        if (traceElements != null && traceElements.length > 0) {
            for (StackTraceElement traceElement : traceElements) {
                sb.append("\r\nat ").append(traceElement);
            }
        }

        return sb.toString();
    }

    /**
     * 打印异常详情 xuJunWei
     *
     * @param throwable ·
     * @param keyword   ·
     */
    public static void printExceptionDetail(Throwable throwable, Object... keyword) {
        StringBuilder sb = new StringBuilder(keyword + " 发生异常, 异常详细信息为: ");
        sb.append(throwable);
        StackTraceElement[] traceElements = throwable.getStackTrace();
        if (traceElements != null && traceElements.length > 0) {
            for (StackTraceElement traceElement : traceElements) {
                sb.append("\r\nat ").append(traceElement);
            }
        }
        Log.d("ExceptionUtils", sb.toString());
        System.err.println("ExceptionUtils: " + sb.toString());
    }

    /**
     * 截取异常消息 xuJunWei
     *
     * @param message ·
     * @param length  ·
     */
    public static String subExceptionMessage(String message, int length) {
        if (StringUtils.isNotEmpty(message)) {
            return message.length() > length ? message.substring(0, length) : message;
        }
        return message;
    }
}
